package com.insigma.business.qrcode.common._provider.impl;

import com.insigma.business.qrcode.common.dto.BuriedPointRequest;
import com.insigma.business.qrcode.common._provider.BuriedPointProvider;
import com.insigma.business.qrcode.common.template.area.BaseProviderImpl;
import com.insigma.business.qrcode.common.util.DateUtils;
import com.insigma.business.qrcode.common.util.RedisUtils;
import com.insigma.business.qrcode.soldier.util.ThreadPoolManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class BuriedPointProviderImpl extends BaseProviderImpl implements BuriedPointProvider {
    private String GLOBAL_PREFIX = "buriedPoint_";
    private String NAME_PREFIX = "buriedPoint_name_";
    private String ALL_PREFIX = "all";
    private String DAILY_PREFIX = "daily";
    private String SECTION_PREFIX = "section";

    private Long expiredTime = 60L;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public String setBuriedPointByWeek(BuriedPointRequest request) {

        if (request == null) {
            return null;
        }

        ThreadPoolManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String weekNum = getWeekNum();
                    String key = GLOBAL_PREFIX + weekNum + "_" + request.getType() + "_" + request.getId();
                    String nameKey = NAME_PREFIX + weekNum + "_" + request.getType() + "_" + request.getId();

                    redisUtils.increment(key, 1L);
                    redisUtils.expire(key, TimeUnit.DAYS.toSeconds(expiredTime));
                    redisUtils.set(nameKey, request.getName(), TimeUnit.DAYS.toSeconds(expiredTime));
                } catch (Exception e) {
                    log.error("error:{}", e);
                }
            }
        });
        return "";
    }

    @Override
    public String setCountPoint(BuriedPointRequest request) {
        return null;
    }

    private String cutIdFromKey(String key) {
        int i = key.lastIndexOf("_");
        return key.substring(i + 1);
    }


    private String getWeekNum() {
        return String.valueOf(DateUtils.getWeekNum());
    }
}
